package com.unohacha.qqj.fzdr.main;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.unohacha.qqj.fzdr.BannerDetailActivity;
import com.unohacha.qqj.fzdr.R;
import com.unohacha.qqj.fzdr.adapter.BaseRVAdapter;
import com.unohacha.qqj.fzdr.adapter.BaseViewHolder;
import com.unohacha.qqj.fzdr.bean.homebean.HomeBannerBean;
import com.unohacha.qqj.fzdr.bean.homebean.HomeExhibitionBean;
import com.unohacha.qqj.fzdr.imp.MyApplication;
import com.unohacha.qqj.fzdr.imp.MyCallBack;
import com.unohacha.qqj.fzdr.imp.UrlConfig;
import com.unohacha.qqj.fzdr.imp.XUtil;
import com.unohacha.qqj.fzdr.main.sends.SendExhibitionActivity;
import com.unohacha.qqj.fzdr.personal.view.activity.ZhanhuiDetailActivity;
import com.unohacha.qqj.fzdr.util.GlideImageLoader;
import com.unohacha.qqj.fzdr.util.Prefer;
import com.unohacha.qqj.fzdr.util.ToastUtils;
import com.unohacha.qqj.mylibrary.base.BaseActivity;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 展会信息 item_exhibition_info
 */
public class ExhibitionInfoActivity extends BaseActivity implements OnRefreshLoadmoreListener {

    @BindView(R.id.common_back)
    ImageView commonBack;
    @BindView(R.id.common_title)
    TextView commonTitle;
    @BindView(R.id.line_supply)
    TextView lineSupply;
    @BindView(R.id.supply_find_rl)
    RelativeLayout supplyFindRl;
    @BindView(R.id.common_title2)
    TextView commonTitle2;
    @BindView(R.id.line_need)
    TextView lineNeed;
    @BindView(R.id.need_find_rl)
    RelativeLayout needFindRl;
    @BindView(R.id.common_right_image)
    ImageView commonRightImage;
    @BindView(R.id.common_right_text)
    TextView commonRightText;
    @BindView(R.id.tab_ll)
    LinearLayout tabLl;
    @BindView(R.id.common_cancle)
    ImageView commonCancle;
    @BindView(R.id.edt_seach)
    EditText edtSeach;
    @BindView(R.id.common_right_search)
    TextView commonRightSearch;
    @BindView(R.id.search_ll)
    LinearLayout searchLl;
    @BindView(R.id.comment_banner)
    Banner banner;
    @BindView(R.id.pt_line)
    ImageView ptLine;
    @BindView(R.id.car_list_recycler)
    RecyclerView carListRecycler;
    @BindView(R.id.mRefreshLayout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.send_iv)
    ImageView sendIv;

    private int page = 1;
    private int typeid = 62;// 61国内  62国外
    private List<HomeBannerBean.DataBean> mBannerAllList = new ArrayList<HomeBannerBean.DataBean>();//banner的集合
    private List<String> mBannerList = new ArrayList<>();
    private List<HomeExhibitionBean.DataBeanX.DataBean> mDataList = new ArrayList<>();
    private BaseRVAdapter mBaseAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_exhibition_info;
    }

    @Override
    protected void initView() {
        super.initView();
//        initRefreshLayout();
        commonRightImage.setImageResource(R.drawable.ic_search_black);
    }

    @Override
    protected void onResume() {
        super.onResume();
        initRefreshLayout();
    }

    private void initRefreshLayout() {
        commonTitle.setText(getResources().getString(R.string.exhibition_gn));
        commonTitle2.setText(getResources().getString(R.string.exhibition_gy));
        mRefreshLayout.setOnRefreshLoadmoreListener(this);
        mRefreshLayout.setRefreshHeader(new ClassicsHeader(this));
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(this));
        carListRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        getExhibitionList(typeid + "", "");
        getBannerData(33);
    }

    @OnClick({R.id.common_back, R.id.need_find_rl, R.id.supply_find_rl,
            R.id.common_right_text, R.id.common_right_image, R.id.common_cancle,
            R.id.common_right_search, R.id.send_iv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.common_back:
                finish();
                break;
            case R.id.need_find_rl://国外
                typeid = 63;
                page = 1;
                lineSupply.setVisibility(View.INVISIBLE);
                lineNeed.setVisibility(View.VISIBLE);
                commonTitle.setTextColor(getResources().getColor(R.color.text_black_666));
                commonTitle2.setTextColor(getResources().getColor(R.color.black));
                getExhibitionList(typeid + "", "");
                break;
            case R.id.supply_find_rl://国内
                typeid = 62;
                page = 1;
                lineSupply.setVisibility(View.VISIBLE);
                lineNeed.setVisibility(View.INVISIBLE);
                commonTitle.setTextColor(getResources().getColor(R.color.text_black_666));
                commonTitle2.setTextColor(getResources().getColor(R.color.black));
                commonTitle.setTextColor(getResources().getColor(R.color.black));
                commonTitle2.setTextColor(getResources().getColor(R.color.text_black_666));
                getExhibitionList(typeid + "", "");
                break;
            case R.id.common_right_image://搜索
                searchLl.setVisibility(View.VISIBLE);
                edtSeach.setText("");
                tabLl.setVisibility(View.GONE);
                break;
            case R.id.common_cancle://取消
                searchLl.setVisibility(View.GONE);
                tabLl.setVisibility(View.VISIBLE);
                edtSeach.setText("");
                break;
            case R.id.common_right_search://搜索按钮
                if (!TextUtils.isEmpty(edtSeach.getText().toString().trim())) {
                    page = 1;
                    getExhibitionList(typeid + "", edtSeach.getText().toString().trim());
                } else {
                    MyToast("请输入搜索内容!");
                    return;
                }
                break;
            case R.id.send_iv://发布
                Intent intent = new Intent(ExhibitionInfoActivity.this,SendExhibitionActivity.class);
                intent.putExtra("app_cate_id",typeid);
                startActivity(intent);
                break;
        }
    }

    //获取banner 集合数据
    private void getBannerData(int typeid) {
        Map<String, Object> params = new HashMap<>();
        params.put("token", Prefer.getInstance().getToken());
        params.put("typeid", typeid);//4-面料供求 5-制造供求 6-原料供求 7-辅料供应 8-人才招聘 29-求职发布
        XUtil.Post(UrlConfig.AD_LIST, params, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("TAG : getBannerData",result);
                try {
                    mRefreshLayout.finishRefresh();
                    mRefreshLayout.resetNoMoreData();
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.optString("code"))) {
                        Gson gson = new Gson();
                        HomeBannerBean bannerBean = gson.fromJson(result, HomeBannerBean.class);
                        if (null != bannerBean) {
                            if (null != mBannerAllList) {
                                mBannerAllList.clear();
                            }
                            mBannerAllList.addAll(bannerBean.getData());
                            setBannerData();
                        }
                        mRefreshLayout.finishLoadmore();
                        mRefreshLayout.finishLoadmoreWithNoMoreData();
                    } else if ("100".equals(jsonObject.optString("code"))) {
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    } else {
                        MyToast(jsonObject.optString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    //设置banner 数据
    private void setBannerData() {
        if (null != mBannerAllList) {
            for (int i = 0; i < mBannerAllList.size(); i++) {
                mBannerList.add(i, mBannerAllList.get(i).getImg_face());
            }
            banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);//设置圆形指示器与标题
            banner.setIndicatorGravity(BannerConfig.CENTER);//设置指示器位置
            banner.setImages(mBannerList);
            banner.setImageLoader(new GlideImageLoader());
            banner.start();

            banner.setOnBannerListener(new OnBannerListener() {
                @Override
                public void OnBannerClick(int position) {
                    //用mBannerAllList集合
                    Intent intent = new Intent(ExhibitionInfoActivity.this, BannerDetailActivity.class);
                    intent.putExtra("url",mBannerAllList.get(position).getUrl());
                    startActivity(intent);
                }
            });
        }
    }


    //获取展会信息列表数据
    private void getExhibitionList(String app_cate_id, String keyword) {
        Map<String, Object> params = new HashMap<>();
        params.put("app_cate_id", typeid);
        if(!TextUtils.isEmpty(edtSeach.getText().toString())){
            params.put("keyword", keyword);
        }
//        params.put("address_id", "");
        params.put("page","1");
        XUtil.Post(UrlConfig.APP_EXHIBITHION_LIST, params, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("TAG:getExhibitionList", result.toString());
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (1 == jsonObject.optInt("code")) {
                        Gson gson = new Gson();
                        HomeExhibitionBean exhibitionBean = gson.fromJson(result, HomeExhibitionBean.class);
                        if (null != exhibitionBean) {
                            if (page == 1) {
                                if (null != mDataList) {
                                    mDataList.clear();
                                }
                                mRefreshLayout.finishRefresh();
                                mRefreshLayout.resetNoMoreData();
                                mDataList.addAll(exhibitionBean.getData().getData());
                            } else {
                                mRefreshLayout.finishLoadmore();
                                mBaseAdapter.notifyDataSetChanged();
                            }
                            setExhibitionAdapter();
                        }
                    } else if (100 == jsonObject.optInt("code")) {
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    } else {
                        if (page == 1) {
                            MyToast(jsonObject.optString("message"));
                            mRefreshLayout.finishRefresh();
                            mRefreshLayout.resetNoMoreData();
                            if (null != mDataList) {
                                mDataList.clear();
                            }
                            mBaseAdapter.notifyDataSetChanged();
                        } else {
                            MyToast(getResources().getString(R.string.no_more_data));
                            mRefreshLayout.finishLoadmore();
                            mRefreshLayout.finishLoadmoreWithNoMoreData();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                Log.d("errorInfo",ex.getMessage())
;                ToastUtils.showT("shibai "+ex.getMessage());
            }
        });
    }

    //设置展会信息数据
    private void setExhibitionAdapter() {
        mBaseAdapter = new BaseRVAdapter(this, mDataList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_exhibition_info;
            }

            @Override
            public void onBind(BaseViewHolder holder, int position) {
                ImageView iv_exhibition = holder.getImageView(R.id.iv_exhibition);
                TextView title_ex = holder.getTextView(R.id.title_ex);
                TextView content_ex = holder.getTextView(R.id.content_ex);
                TextView time_ex = holder.getTextView(R.id.time_ex);
                if (null != mDataList) {
                    Glide.with(ExhibitionInfoActivity.this).load(mDataList.get(position).getThumb())
                            .into(iv_exhibition);
                    title_ex.setText(mDataList.get(position).getTitle());
                    content_ex.setText(mDataList.get(position).getContent());
                    time_ex.setText(mDataList.get(position).getExhibition_time());
                }
            }
        };
        carListRecycler.setAdapter(mBaseAdapter);
        mBaseAdapter.addItemClickListener(new BaseRVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
                Intent intent = new Intent(ExhibitionInfoActivity.this, ZhanhuiDetailActivity.class);
                intent.putExtra("id", mDataList.get(position).getId() + "");
                startActivity(intent);
            }
        });
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                page++;
                getExhibitionList(typeid + "", "");
            }
        }, 2000);
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                page = 1;
                getExhibitionList(typeid + "", "");
            }
        }, 2000);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

}
